package grid.puzzle;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.GridView;

public class GridPuzzleActivity extends Activity implements
		OnItemClickListener, OnClickListener {
	GridAdapter gridAdapter;
	GridView gridView;
	Button shuffleButton;
	Chronometer chronometer;

	private int gridSize = 4;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		gridView = (GridView) findViewById(R.id.dashBoardGridView);
		shuffleButton = (Button) findViewById(R.id.shuffleButton);
		chronometer = (Chronometer) findViewById(R.id.chronometer);

		gridAdapter = new GridAdapter(this, gridSize);
		gridView.setAdapter(gridAdapter);
		gridView.setNumColumns(gridSize);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));

		gridView.setOnItemClickListener(this);
		shuffleButton.setOnClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (gridAdapter.isShufflingOn()) {
			stopShuffling();
		}

		gridAdapter.move(position);

		if (gridAdapter.isSolved()) {
			chronometer.stop();
			shuffleButton.setText("TADAAAA");
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.shuffleButton:
			if (gridAdapter.isShufflingOn()) {
				stopShuffling();
			} else {
				startShuffling();
			}
			return;

		default:
			return;
		}
	}

	private void startShuffling() {
		gridAdapter.startShuffling();
		shuffleButton.setText("Stop");
	}

	private void stopShuffling() {
		gridAdapter.stopShuffling();
		chronometer.setBase(SystemClock.elapsedRealtime());
		chronometer.start();
		shuffleButton.setText("Shuffle");
	}
}